<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import Particles from '@/components/Particles.vue'
import type { FormInst, FormItemRule } from 'naive-ui'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { useRegisterStore } from '@/stores/register'
import { Base64 } from 'js-base64'
import Cookies from 'js-cookie'

const registerStore = useRegisterStore()
const userStore = useUserStore()
const bodyStyle = {
    width: '600px'
}

const showModal = ref(false)

const formRef = ref<FormInst | null>(null)
const formRef2 = ref<FormInst | null>(null)
const message = useMessage()
const model = ref({
    username: null,
    password: null,
    inputValue: null,
    remember: []
})

const rules = {
    username: [
        {
            required: true,
            validator(rule: FormItemRule, value: string) {
                if (!value) {
                    return new Error('请输入账户')
                }
                return true
            },
            trigger: ['input', 'blur']
        }
    ],
    password: [
        {
            required: true,
            validator(rule: FormItemRule, value: string) {
                const regPass = /^[a-zA-Z]\w{5,17}$/
                if (!value) {
                    return new Error('请输入密码')
                } else if (!(regPass.test(value))) {
                    return new Error('请输入以字母开头，长度在6~18位之间，只能包含字符、数字和下划线的密码')
                }
                return true
            },
            trigger: ['input', 'blur']
        },
    ],
    inputValue: {
        required: true,
        trigger: ['input', 'blur'],
        message: '请输入店铺名称'
    }
}

// 进入登录页面时检测cookies是否存有有用户名和密码
const hasUserCodeOrPassword = () => {
    if (Cookies.get('userName') && Cookies.get('userPassword')) {
        model.value.username = Cookies.get('userName')
        model.value.password = Base64.decode(Cookies.get('userPassword'))//解密
        model.value.remember[0] = 'remember'
    }
}
onMounted(() => {
    hasUserCodeOrPassword()
})


const router = useRouter()
const submit = (e: MouseEvent) => {
    e.preventDefault()
    let isChecked = model.value.remember.length ? true : false
    formRef.value?.validate(async (errors) => {
        if (!errors) {
            const res = await userStore.doLogin({ loginName: model.value.username, loginKey: model.value.password })
            if (res?.success) {
                router.push({ path: '/' })
                if (isChecked) {
                    Cookies.set('userName', model.value.username)
                    Cookies.set(
                        'userPassword',
                        Base64.encode(model.value.password),		//base加密
                    )
                } else {
                    Cookies.remove('userName')
                    Cookies.remove('userPassword')
                }
            } else {
                message.error(res?.message)
            }
        } else {
            console.log(errors)
            message.error('验证失败')
        }
    })
}

const checkStatus = async () => {
    formRef2.value?.validate(async (errors) => {
        if (!errors) {
            const res = await registerStore.checkStatus(model.value.inputValue)
            const status = res?.data[0]?.status
            if (status == 0) {
                message.error('审核中，请耐心等待');
            } else if (status == 1) {
                message.success('审核通过，请登录');
            } else if (status == 2) {
                message.error('审核未通过，原因是:' + res.data[0].refuse);
            } else {
                message.error('未提交审核，请注册账号');
            }
        } else {
            console.log(errors)
        }
    })
}

</script>
                
<template>

    <Particles />

    <n-card class="box-card">
        <template #header>
            <div class="card-header">
                <img class="main-img" src="../../static/images/logo-main.jpg" />
            </div>
            <n-space vertical>
                <n-form ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="60">
                    <n-form-item label="" path="username" style="height: 70px;">
                        <n-input v-model:value="model.username" placeholder="请输入账户" autofocus>
                            <template #prefix>
                                <span class="iconfont icon-zhanghu"></span>
                            </template>
                        </n-input>
                    </n-form-item>
                    <n-form-item label="" path="password" style="height: 70px;">
                        <n-input v-model:value="model.password" type="password" placeholder="请输入密码">
                            <template #prefix>
                                <span class="iconfont icon-mima"></span>
                            </template>
                        </n-input>
                    </n-form-item>
                    <n-space justify="space-between">
                        <n-checkbox-group v-model:value="model.remember">
                            <n-checkbox value="remember">
                                记住密码
                            </n-checkbox>
                        </n-checkbox-group>
                        <n-button quaternary>
                            忘记密码
                        </n-button>
                    </n-space>
                    <n-space justify="center">
                        <n-button type="primary" dashed style="width: 400px;" @click="submit">
                            登录
                        </n-button>
                    </n-space>
                    <n-space justify="space-between" style="margin-top: 25px;">
                        <n-button dashed strong type="info" @click="$router.push('/register')">
                            商户注册
                        </n-button>
                        <n-button dashed strong type="warning" @click="showModal = true">
                            查看商户注册结果
                        </n-button>
                    </n-space>
                </n-form>
            </n-space>
        </template>
    </n-card>

    <n-modal v-model:show="showModal" class="custom-card" preset="card" :style="bodyStyle" title="查看注册结果" size="huge"
        :bordered="false">
        <n-form ref="formRef2" :model="model" :rules="rules" label-placement="left">
            <n-form-item label="商户名称：" path="inputValue">
                <n-input v-model:value="model.inputValue" placeholder="请输入商户名称" autofocus clearable />
            </n-form-item>
            <n-space justify="end">
                <n-button type="success" @click="checkStatus">
                    确定
                </n-button>
            </n-space>
        </n-form>
    </n-modal>

</template>
                
<style scoped>
.box-card {
    width: 35%;
    margin: 90px auto;
    opacity: 0.9;
}

.main-img {
    width: 100px;
    margin: 0 auto;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.demo-ruleForm {
    padding-right: 25px;
}

.form-btn {
    display: flex;
}
</style>
